added samples
[windows-sources.git] / sdk / samples / all in on code / Visual Studio 2010 / VBWebBrowserAutomation / XMLSerialization.vb
blobb81a0be413261924f9c30946c111dd08085a5ad5
1 '*************************** Module Header ******************************'
2 ' Module Name: XMLSerialization.vb
3 ' Project: VBWebBrowserAutomation
4 ' Copyright (c) Microsoft Corporation.
5 '
6 ' This class is used to serialize an object to an XML file or deserialize an XML
7 ' file to an object.
8 '
9 ' This source is subject to the Microsoft Public License.
10 ' See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
11 ' All other rights reserved.
13 ' THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
14 ' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
15 ' WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
16 '*************************************************************************'
18 Imports System.IO
19 Imports System.Xml.Serialization
21 Public Class XMLSerialization(Of T)
23 ''' <summary>
24 ''' Serialize an object to an XML file.
25 ''' </summary>
26 Public Shared Function SerializeFromObjectToXML(ByVal obj As T,
27 ByVal filepath As String) As Boolean
28 If obj Is Nothing Then
29 Throw New ArgumentException("The object to serialize could not be null!")
30 End If
32 Dim successed As Boolean = False
33 Dim objType As Type = obj.GetType()
34 Using fs As New FileStream(filepath, FileMode.Create, FileAccess.ReadWrite)
35 Dim xs As New XmlSerializer(objType)
36 xs.Serialize(fs, obj)
37 successed = True
38 End Using
40 Return successed
41 End Function
43 ''' <summary>
44 ''' Deserialize an XML file to an object.
45 ''' </summary>
46 Public Shared Function DeserializeFromXMLToObject(ByVal filepath As String) As T
47 If Not File.Exists(filepath) Then
48 Throw New ArgumentException("The file does not exist!")
49 End If
51 Dim obj As T
52 Using fs As New FileStream(filepath, FileMode.Open)
53 Dim xs As New XmlSerializer(GetType(T))
54 obj = CType(xs.Deserialize(fs), T)
55 End Using
56 Return obj
57 End Function
59 End Class